#include "BeamShootStrategy.h"
#include "WeaponBank.h"
#include "Bullet.h"
#include "MathUtil.h"


BeamShootStrategy::BeamShootStrategy(void)
{
	_weapon = NULL;
	_positionShoot = CCPointZero;
	_angleOpen = 90;
	_direct = ccp(0, -1);
	_numberBullet = 4;
	_timeDelay = 1;
	_timeDelayStart = 0;
}


BeamShootStrategy::~BeamShootStrategy(void)
{
	CC_SAFE_RELEASE(_weapon);
}

bool BeamShootStrategy::init()
{
	if (!BaseStrategy::init())
		return false;
	return true;
}

void BeamShootStrategy::parseXml( xml_node node )
{
	// Parse weapon
	char* weapon = (char*)node.child("Weapon").text().as_string();
	Weapon* wp = WeaponBank::sharedWeaponBank()->getWeapon(weapon);
	setWeapon(wp);
	// Time Delay
	float timeDelay = node.child("TimeDelay").text().as_float();
	setTimeDelay(timeDelay);
	setTimeDelayStart(node.child("TimeDelayStart").text().as_float());
	// Position shoot
	int posX = node.child("PositionShoot").child("X").text().as_int();
	int posY = node.child("PositionShoot").child("Y").text().as_int();
	setPositionShoot(ccp(posX, posY));
	// Direct
	posX = node.child("Direct").child("X").text().as_int();
	posY = node.child("Direct").child("Y").text().as_int();
	setDirect(ccp(posX, posY));
	// Angle Open
	float angle = node.child("AngleOpen").text().as_float();
	setAngleOpen(angle);
	// NumberShoot
	int number = node.child("NumberBullet").text().as_int();
	setNumberBullet(number);

}

void BeamShootStrategy::onEnter()
{
	BaseStrategy::onEnter();
	runAction(CCSequence::create(CCDelayTime::create(_timeDelayStart), CCCallFuncN::create(this, SEL_CallFuncN(&BeamShootStrategy::startStrategy)), NULL));
}

void BeamShootStrategy::onExit()
{
	BaseStrategy::onExit();
	unschedule(SEL_SCHEDULE(&BeamShootStrategy::shoot));
}

void BeamShootStrategy::shoot( float dt )
{
	float deltaAngle = _angleOpen / (_numberBullet - 1);
	float startAngle = _angleOpen / 2;

	for (int i = 0; i < _numberBullet; i++)
	{
		float angle = startAngle - i * deltaAngle;
		Bullet* bullet = dynamic_cast<Bullet*>(_weapon->addBullet()->objectAtIndex(0));
		bullet->setPosition(getOwner()->getPosition() + _positionShoot + bullet->getPosition());
		CCPoint vel = MathUtil::rotateVector(bullet->getVelocity(), MathUtil::DegreeToRad(angle));
		bullet->setVelocity(vel);
		
	}

}

Weapon* BeamShootStrategy::getWeapon()
{
	return _weapon;
}

void BeamShootStrategy::setWeapon(Weapon* var)
{
	if (_weapon != var)
	{
		removeChild(_weapon);
		CC_SAFE_RETAIN(var);
		CC_SAFE_RELEASE(_weapon);
		_weapon = var;
		addChild(_weapon);
	}
}

void BeamShootStrategy::startStrategy( CCNode* sender )
{
	shoot(_timeDelay);
	schedule(SEL_SCHEDULE(&BeamShootStrategy::shoot), _timeDelay);
}
